<?php

namespace App\Console\Commands\Common\Ekb;

use App\Library\Common\MemoryUsageTools;
use App\Models\Ekb\EkbBranchBankModel;
use App\Remote\EKuaiBao\EKuaiBaoRemote;
use Box\Spout\Reader\Common\Creator\ReaderEntityFactory;
use Exception;
use GuzzleHttp\Exception\GuzzleException;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
use Psr\Container\ContainerExceptionInterface;
use Psr\Container\NotFoundExceptionInterface;

class SynchronousBranchBankCommand extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'ekb:synchronousBranchBankCommand';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '易快报：支行信息同步';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return int
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface|GuzzleException
     */
    public function handle(): int
    {
        try {
            ini_set('memory_limit', '200M');
            $initMemoryUsage = MemoryUsageTools::getNowMemoryUsage();

            $branchInfo    = EKuaiBaoRemote::getAllBranch();
            $branchLinkUrl = $branchInfo["url"];
            $formatDate    = formatDateYmd(time(), "-");
            $saveDir       = getTmpDir("ekb-branch");
            $fileSystem    = getFileSystem();
            if (!$fileSystem->isDirectory($saveDir)) {
                $fileSystem->makeDirectory($saveDir, 0777, true);
            }
            $filePath = vsprintf(
                "%s/%s.%s", [
                    $saveDir,
                    $formatDate,
                    explode(".", parse_url($branchLinkUrl)["path"])[1]
                ]
            );
            $fileSystem->put($filePath, file_get_contents($branchLinkUrl));

//            $filePath   = "/www/wps/tiger-api/storage/ekb-branch/2023-09-18.xlsx";
            $insertData = [];
            $reader     = ReaderEntityFactory::createXLSXReader();

            $reader->open($filePath);
            $this->getOutput()->info("执行清空表操作 ...");
            DB::table((new EkbBranchBankModel())->getTable())->truncate();
            $this->getOutput()->info("执行清空表操作  完成");

            foreach ($reader->getSheetIterator() as $sheet) {
                foreach ($sheet->getRowIterator() as $k => $row) {
                    if ($k > 1) {
                        $cells = $row->getCells();
                        array_push($insertData, [
                            "branchId"   => $cells[0]->getValue(),
                            "branchName" => $cells[1]->getValue(),
                            "bankLinkNo" => $cells[2]->getValue(),
                            "cityId"     => $cells[3]->getValue(),
                            "bankId"     => $cells[4]->getValue(),
                            "updateTime" => $cells[5]->getValue(),
                        ]);
                    }

                    if (count($insertData) >= 1000) {
                        $this->getOutput()->info("执行插入操作【" . count($insertData) . "】 ...");
                        EkbBranchBankModel::query()->insert($insertData);
                        $this->getOutput()->info("执行插入操作【" . count($insertData) . "】 完成");
                        $insertData = [];
                    }
                }
            }


            if (!empty($insertData)) {
                $this->getOutput()->info("执行插入操作【" . count($insertData) . "】 ...");
                EkbBranchBankModel::query()->insert($insertData);
                $this->getOutput()->info("执行插入操作【" . count($insertData) . "】 完成");
                $insertData = [];
            }

            $reader->close();
            $endMemoryUsage = MemoryUsageTools::getNowMemoryUsage();
            logInfo("易快报支行同步成功", collect([
                "initMemoryUsage" => $initMemoryUsage,
                "endMemoryUsage"  => $endMemoryUsage,
            ]), true, true);

        } catch (Exception $exception) {
            logException("易快报支行同步 失败", $exception, null, true, true);
        }
        return 0;
    }
}
